//  @@@ web_export_view custom JS @@@
//#############################################################################
//    
//    Copyright (C) 2012 Agile Business Group sagl (<http://www.agilebg.com>)
//    Copyright (C) 2012 Therp BV (<http://therp.nl>)
//
//    Part of codes has been changed by Rainsoft(<kfx2007@163.com>)
//
//    This program is free software: you can redistribute it and/or modify
//    it under the terms of the GNU Affero General Public License as published
//    by the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.
//
//    This program is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU Affero General Public License for more details.
//
//    You should have received a copy of the GNU Affero General Public License
//    along with this program.  If not, see <http://www.gnu.org/licenses/>.
//
//#############################################################################

odoo.define('web.export.view',function(require){
    'use strict';

    var core = require('web.core');
    var _t = core._t;
    var Widget = require('web.Widget');
    var QWeb = core.qweb;
    var Sidebar = require('web.Sidebar');
    var formats = require('web.formats');

    Sidebar.include({
        redraw:function(){
            var self = this;
            this._super.apply(this, arguments);
            //官方脑子有屎，换个版本换种写法，谁跟你们玩谁完蛋。
            self.$('.btn-group').parent().append(QWeb.render('AddExportViewMain', {widget: self}));
            self.$('.oe_sidebar_export_view_xls').click('click', self.on_sidebar_export_view_xls);
            self.$('.oe_sidebar_export_view_xls_all').click('click', self.on_sidebar_export_view_xls_all);
        },

        on_sidebar_export_view_xls_all: function(){
            var self = this;
            self.on_sidebar_export_view_xls_excute(true);
        },

        on_sidebar_export_view_xls: function(){
            var self = this;
            self.on_sidebar_export_view_xls_excute(false);
        },
        
        on_sidebar_export_view_xls_excute: function(all) {
            // Select the first list of the current (form) view
            // or assume the main view is a list view and use that
            var self = this,
            view = this.getParent(),
            children = view.getChildren();

            if (children) {
                children.every(function(child) {
                    if (child.field && child.field.type == 'one2many') {
                        if(child.$el.css('display') == 'none'){
                            return true;
                        }else{
                            var isHide = false;
                            child.$el.parents("div").each(function(){
                                if($(this).css('display') == 'none'){
                                    isHide = true;
                                 }
                            });
                            if(isHide){
                                return true;
                            }
                        }
                        view = child.viewmanager.views.list.controller;
                        var isHasView = true;
                        return false; // break out of the loop
                    }
                    if (child.field && child.field.type == 'many2many') {

                         if(child.$el.css('display') == 'none'){
                            return true;
                        }else{
                            var isHide = false;
                            child.$el.parent("div").each(function(){
                                if($(this).css('display') == 'none'){
                                    isHide = true;
                                 }
                            });
                            if(isHide){
                                return true;
                            }
                        }

                        view = child.list_view;
                        var isHasView = true;
                        return false; // break out of the loop
                    }
                    return true;
                });
            }

            var export_columns_keys = [];
            var export_columns_names = [];

            if(!view){
                alert("很抱歉！当前页面没有可导出的列表！");
                return false;
            }
            $.each(view.visible_columns, function(){
                if(this.tag=='field'){
                    // non-fields like `_group` or buttons
                    export_columns_keys.push(this.id);
                    export_columns_names.push(this.string);
                }
            });
            var rows = view.$el.find('.o_list_view > tbody > tr');
            var export_rows = [];
            $.each(rows,function(){
                var $row = $(this);
                // find only rows with data
                if($row.attr('data-id')){
                    var export_row = [];
                    //他娘的JQuery高版本不支持attr了 js果然坑爹
                    var checked = $row.find('div.o_checkbox input[type=checkbox]').prop("checked");
                    if(all || checked){
                        checked = "checked"
                    }

                    if (children && checked === "checked"){
                        $.each(export_columns_keys,function(){
                            var cell = $row.find('td[data-field="'+this+'"]').get(0);
                            var text = cell.text || cell.textContent || cell.innerHTML || "";
                            if (this=="sequence"){
                                export_row.push('');
                            }
                            else if (cell.classList.contains("o_list_number")){
                                export_row.push(formats.parse_value(text, {'type': "float"}));
                            }
                            else if ($(cell).find('div.o_checkbox').length>0){
                                if($(cell).find('input').get(0).checked){
                                    export_row.push(_t("True"));
                                }
                                else {
                                    export_row.push(_t("False"));
                                }
                            }
                            else{
                               export_row.push(text.trim());
                            }
                        });
                        export_rows.push(export_row);
                    };
                }
            });
            $.blockUI();
            view.session.get_file({
                url: '/web/export/xls_view',
                data: {data: JSON.stringify({
                    model : view.model,
                    headers : export_columns_names,
                    rows : export_rows
                })},
                complete: $.unblockUI
            });
        }
    });
});